<template>
	<view @click="handleClick" class="i-floatBut" @touchstart="touchstart" @touchmove.stop="touchmove"
		@touchend="touchend" :style="{transform: 'translate('+ (moveX + 'px') + ',' + (moveY + 'px') +')'}">
		<slot></slot>
	</view>
</template>

<script lang="ts" setup>
	import {
		defineProps,
		defineEmits,
		ref
	} from 'vue'
	import _ from 'lodash'
	import { getWindowHeight } from '../../utils/common';
	const props = defineProps({
		bodyWeight: {
			type: Number,
			default: 52
		},
		bodyHeight: {
			type: Number,
			default: 52
		}
	})
	const isTouch = ref(false)
	const moveX = ref(0)
	const moveY = ref(0)

	const windowHeight = getWindowHeight()
	const emit = defineEmits(['click'])
	const handleClick = () => {
		emit('click')
	}

	const windowWidth = uni.getSystemInfoSync().windowWidth
	const touchstart = () => {
		isTouch.value = true
	}

	const touchmov = (e : { touches : any[], currentTarget : {} }) => {
		if (isTouch.value) {
			let y = 0
			// #ifdef APP-PLUS
			y = -(windowHeight - e.touches[0].clientY - props.bodyHeight - 24)
			moveY.value = y > (props.bodyHeight / 2 - 24) ? (props.bodyHeight / 2 - 24) : y < - (windowHeight - props.bodyHeight - 88 ) ? - (windowHeight - props.bodyHeight - 88) : y
			// #endif

			// #ifdef MP-WEIXIN
			y = -(windowHeight - e.touches[0].clientY - (props.bodyHeight / 2 - 24))
			moveY.value = y > (props.bodyHeight - 48) ? (props.bodyHeight - 48) : y < - (windowHeight - props.bodyHeight / 2) ? - (windowHeight - props.bodyHeight / 2) : y

			// #endif
			const x = -(windowWidth - e.touches[0].clientX - props.bodyWeight / 2 - 16)
			moveX.value = x > (props.bodyWeight / 2 - 16) ? (props.bodyWeight / 2 - 16) : x < - (windowWidth - (props.bodyWeight + 32)) ? - (windowWidth - (props.bodyWeight + 32)) : x
		}
	}

	const touchmove = _.throttle(touchmov, 20, { leading: true, trailing: false })

	const touchend = () => {
		isTouch.value = false
	}
</script>

<style lang="scss" scoped>
	.i-floatBut {
		position: fixed;
		bottom: 24px;
		right: 18px;
		z-index: 90;
	}
</style>